package com.duke.business.service.sb01.script2platform.app;

import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author gjy
 * @create 2025-08-14 16:32
 */
@Service
public class ScriptService {
    public void executeScript(ScriptRequest request) throws Exception {
        // 1. 创建新的 ClassLoader
        File rootDir = new File(request.getScriptPath());
        URL[] urls = { rootDir.toURI().toURL() };
        ClassLoader scriptLoader = new URLClassLoader(urls);
        // 打印 ClassLoader 信息和 hashCode
        System.out.println("Script ClassLoader: " + scriptLoader + ", hashCode=" + scriptLoader.hashCode());

        // 2. 加载脚本类
        Class<?> scriptClass = scriptLoader.loadClass("com.duke.business.service.sb01.script2platform.scripts.ScriptTestObj");
//        Class<?> scriptClass = scriptLoader.loadClass(ScriptTestObj.class.getName());
        System.out.println("Loaded class: " + scriptClass + ", classLoader=" + scriptClass.getClassLoader());

        // 3. 创建实例并调用 run()
        Object instance = scriptClass.getConstructor(String.class).newInstance(request.getMessage());
        scriptClass.getMethod("run").invoke(instance);

        // 4. 手动释放 ClassLoader（可选，防止内存泄漏）
        if (scriptLoader instanceof AutoCloseable) {
//            ((AutoCloseable) scriptLoader).close();
            System.out.println("ClassLoader closed: " + scriptLoader);
        }
    }
}
